package com.jdy.haoduoaiteacher.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.Toast;

import com.jdy.haoduoaiteacher.intface.IAsyncTask;
import com.jdy.haoduoaiteacher.util.CustomAsyncTask;
import com.jdy.haoduoaiteacher.util.HttpUtils;
import com.jdy.haoduoaiteacher.util.ResponseResult;
import com.jdy.haoduoaiteacher.util.StringInfoMatch;
import com.jdy.haoduoaiteacher.util.Tools;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.droidparts.widget.ClearableEditText;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

//import com.jdy.haoduoaiteacher.R;

/**
 * Get lost password back.
 * 
 * @author zp @ 2015-6-4 下午2:19:43
 */
public class GetLostPasswordActivity extends BaseActivity {

  private Animation pressedAnimation;

  @InjectView(id = R.id.get_verify_code, click = true)
  private Button getVerifyCodeBtn;
  @InjectView(id = R.id.btn_submit_ok, click = true)
  private Button btn_submit_ok;
  @InjectView(id = R.id.input_tel, click = true)
  private ClearableEditText input_tel;
  @InjectView(id = R.id.input_verifycode, click = true)
  private ClearableEditText input_verifycode;
  @InjectView(id = R.id.input_newpassword, click = true)
  private ClearableEditText input_newpassword;

  private boolean isInCountDown = false;
  private final StringInfoMatch stringMatch = new StringInfoMatch();

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.get_lost_password_layout);
    initView();
    setTitle("忘记密码");
  }

  private void startCountDown() {
    isInCountDown = true;
    getVerifyCodeBtn.setEnabled(false);
    new CountDownTimer(100000, 1000) {
      @Override
      public void onTick(long millisUntilFinished) {
        getVerifyCodeBtn.setText(millisUntilFinished / 1000 + "秒后\n重取");
      }

      @Override
      public void onFinish() {
        isInCountDown = false;
        getVerifyCodeBtn.setEnabled(true);
        getVerifyCodeBtn.setText(getString(R.string.get_captcha));
      }
    }.start();
  }

  private void updateBtnStatus() {
    if (Tools.isEmpty(input_tel.getText().toString())) {
      getVerifyCodeBtn.setEnabled(false);
    } else {

      if (!isInCountDown) {
        getVerifyCodeBtn.setEnabled(true);
      }
    }

    if (Tools.isEmpty(input_tel.getText().toString())
        || Tools.isEmpty(input_verifycode.getText().toString())
        || Tools.isEmpty(input_newpassword.getText().toString())
        || input_newpassword.getText().toString().length() < 6) {
      btn_submit_ok.setEnabled(false);
    } else {
      btn_submit_ok.setEnabled(true);
    }
  }

  private void addEditTextListener() {
    input_tel.addTextChangedListener(new TextWatcher() {
      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {
      }

      @Override
      public void beforeTextChanged(CharSequence s, int start, int count,
          int after) {
      }

      @Override
      public void afterTextChanged(Editable s) {
        updateBtnStatus();
      }
    });

    input_verifycode.addTextChangedListener(new TextWatcher() {
      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {
      }

      @Override
      public void beforeTextChanged(CharSequence s, int start, int count,
          int after) {
      }

      @Override
      public void afterTextChanged(Editable s) {
        updateBtnStatus();
      }
    });

    input_newpassword.addTextChangedListener(new TextWatcher() {
      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {
      }

      @Override
      public void beforeTextChanged(CharSequence s, int start, int count,
          int after) {
      }

      @Override
      public void afterTextChanged(Editable s) {
        updateBtnStatus();
      }
    });
  }

  private void initView() {
    pressedAnimation = AnimationUtils.loadAnimation(this, R.anim.anim_pressed);

    updateBtnStatus();
    addEditTextListener();

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
      @Override
      public void run() {
        InputMethodManager inputManager = (InputMethodManager) input_tel
            .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(input_tel, 0);
      }
    }, 200);

    getVerifyCodeBtn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        if (Tools.isEmpty(input_tel.getText().toString())) {
          toastShow(getString(R.string.input_tel));
          return;
        }

        if (!stringMatch.ifMatchPhoneFormat(input_tel.getText().toString()
            .trim())) {
          toastShow("请输入正确的手机号码！");
          return;
        }

        v.startAnimation(pressedAnimation);
        pressedAnimation.setAnimationListener(new AnimationListener() {
          @Override
          public void onAnimationStart(Animation animation) {

          }

          @Override
          public void onAnimationRepeat(Animation animation) {

          }

          @Override
          public void onAnimationEnd(Animation animation) {
            new CustomAsyncTask(GetLostPasswordActivity.this, new IAsyncTask() {
              @Override
              public void onRecieveData(Activity activity, ResponseResult result) {

                // toastShow(result.data);
                if (result.isSuccess())
                  startCountDown();
              }

              @Override
              public ResponseResult doInbackground(Activity activity) {

                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put(HttpUtils.TAG_MOBILE_I,
                    String.valueOf(input_tel.getText().toString()));
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

                param_.put("type", 1);

                return HttpUtils.startRequest(HttpUtils.HOST_API
                    + HttpUtils.GET_VERIY_CODE_METHOD_GET, param_,
                    HttpUtils.TAG_GET_REQUEST);
              }
            }).execute();
          }
        });
      }
    });

    btn_submit_ok.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        if (Tools.isEmpty(input_verifycode.getText().toString())) {
          Toast
              .makeText(
                  getApplicationContext(),
                  GetLostPasswordActivity.this
                      .getString(R.string.input_verifycode), Toast.LENGTH_SHORT)
              .show();
          return;
        }

        if (Tools.isEmpty(input_newpassword.getText().toString())) {
          toastShow(getString(R.string.input_password));
          return;
        }

        new CustomAsyncTask(GetLostPasswordActivity.this, new IAsyncTask() {
          @Override
          public void onRecieveData(Activity activity, ResponseResult result) {

            toastShow(result.data);

            if (result.isSuccess()) {
              Intent intent = new Intent(GetLostPasswordActivity.this,
                  LoginActivity.class);
              intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
              startActivity(intent);

              overridePendingTransition(R.anim.push_left_in,
                  R.anim.push_left_out);

              finish();
            }
          }

          @Override
          public ResponseResult doInbackground(Activity activity) {
            String mobile = input_tel.getText().toString();
            String verifyCode = input_verifycode.getText().toString();
            String newPwd = input_newpassword.getText().toString();

            HashMap<String, Object> param_ = new HashMap<String, Object>();

            param_.put(HttpUtils.TAG_MOBILE_I, mobile);
            param_.put("new_password", newPwd);
            param_.put(HttpUtils.TAG_VERIFY_CODE_I, verifyCode);
            param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

            return HttpUtils.startRequest(HttpUtils.HOST_API
                + HttpUtils.MODIFY_PASSWARD_METHOD_POST, param_,
                HttpUtils.TAG_POST_REQUEST);
          }
        }).execute();
      }
    });
  }
}
